<?php
namespace Home\Controller;
use Think\Controller;
use Think\Image;
use Home\Model\IndexModel;
use Weixin\Wechat;
use Weixin\WechatAuth;

class IndexController extends CommonController {
   
//class IndexController extends Controller {
    public function index(){
		$token = 'weixin'; //微信后台填写的TOKEN
		/* 加载微信SDK */
		$wechat = new Wechat($token);
		/* 获取请求信息 */
		$data = $wechat->request();
		if($data && is_array($data)){
		    //在这里你可以分析用户发送过来的数据来决定需要做出什么样的回复
		   
		    /* 响应当前请求(自动回复) */
		   $this->responseWhat($wechat, $data);
		}
		
    }
    //根据消息类型回复
	private function responseWhat($wechat, $data){
        switch ($data['MsgType']) {
            case Wechat::MSG_TYPE_EVENT:
                switch ($data['Event']) {
                    //用户关注事件（将用户存到数据库）
                    case Wechat::MSG_EVENT_SUBSCRIBE:
                    // //获取到用户的openId值
                    $openid=$data['FromUserName'];
                    //获取用户信息数组
                    $userdata = $this->getinfobyopenid($openid);
                     //把关注用户的信息写入数据库
                    $user = new IndexModel('user','kl_');
                    //暂时只要存openid，因为如果存了昵称的话，用户如果改了昵称就显示错了
                    $info = $user->putUserData($openid);
                    $wechat->replyText("你好，".$userdata->nickname.",欢迎使用快来优惠分享平台");
                    // $wechat->replyText($openid);
                        break;
                    case Wechat::MSG_EVENT_UNSUBSCRIBE:
                        //取消关注，记录日志
                        break;
                    case Wechat::MSG_EVENT_VIEW:
                        echo 1;
                        break;
                    default:
                        $wechat->replyText("欢迎访问麦当苗儿公众平台！您的事件类型：{$data['Event']}，EventKey：{$data['EventKey']}");
                        break;
                }
                break;

            case Wechat::MSG_TYPE_TEXT:
                switch ($data['Content']) {
                    case '文本':
                    //用户回复文本，获取用户信息
                    
                    $openid=$data['FromUserName'];
                    //获取用户信息数组
                    $userdata = $this->getinfobyopenid($openid);
                     //把关注用户的信息写入数据库
                    $user = new IndexModel('user','kl_');
                    //暂时只要存openid，因为如果存了昵称的话，用户如果改了昵称就显示错了
                    $info = $user->putUserData($openid);

                    $wechat->replyText("你好，".$userdata->nickname.",欢迎使用快来优惠分享平台");
                    // $test=$mem->get($this->appSecret);

                        break;
                    
                    default:
                        $wechat->replyText("欢迎访问快来优惠分享平台！");
                        break;
                }
                break;
            case Wechat::MSG_TYPE_IMAGE:
                 $wechat->replyText("您成功上传了图片");
            default:
                # code...
                break;
        }
    }
    public function test(){

        $this->display("comment");
    }
    public function testjs(){
        $val = I("post.image");
        $sql = "insert into test values ($val)";
        $test=M("Test");
        $data['serid'] = $val;
        $test->data($data)->add();
        echo $val;
    }

    /**
     * 资源文件上传方法
     * @param  string $type 上传的资源类型
     * @return string       媒体资源ID
     */
    private function upload($type){
        $appid     = 'wx603db1a9748a186b';
        $appsecret = '59f45a3bb1ecd4fee39b06ca4c2477a0';

        $token = session("token");

        if($token){
            $auth = new WechatAuth($appid, $appsecret, $token);
        } else {
            $auth  = new WechatAuth($appid, $appsecret);
            $token = $auth->getAccessToken();

            session(array('expire' => $token['expires_in']));
            session("token", $token['access_token']);
        }

        switch ($type) {
            case 'image':
                $filename = './Public/image.jpg';
                $media    = $auth->materialAddMaterial($filename, $type);
                break;

            case 'voice':
                $filename = './Public/voice.mp3';
                $media    = $auth->materialAddMaterial($filename, $type);
                break;

            case 'video':
                $filename    = './Public/video.mp4';
                $discription = array('title' => '视频标题', 'introduction' => '视频描述');
                $media       = $auth->materialAddMaterial($filename, $type, $discription);
                break;

            case 'thumb':
                $filename = './Public/music.jpg';
                $media    = $auth->materialAddMaterial($filename, $type);
                break;
            
            default:
                return '';
        }

        if($media["errcode"] == 42001){ //access_token expired
            session("token", null);
            $this->upload($type);
        }

        return $media['media_id'];
    }


    //从微信服务器上获取媒体文件
    // public function get_media($access_token, $media_id){
    //     $url = 'https://api.weixin.qq.com/cgi-bin/media/get?access_token='.$access_token.'&media_id='.$media_id;
    //     $content = file_get_contents($url);
    //     return $content;
       
    // }


}